import { useState, useRef, useEffect } from 'react'
export default function useSyncExternalStore(subscribe, getSnapshot) {
	const [, forceUpdate] = useState(null)
	const inst = useRef(null)
	const nextValue = getSnapshot()
	inst.current = {
		value: nextValue,
		getSnapshot,
	}

	/* 检查是否更新 */
	const checkIfSnapshotChanged = () => {
		try {
			const { value, getSnapshot } = inst.current
			/* 最新的快照信息 */
			const nextValue = getSnapshot()
			return !Object.is(nextValue, value)
		} catch (err) {
			return true
		}
	}
	/* 处理 store 改变 */
	const handleStoreChange = () => {
		if (checkIfSnapshotChanged()) {
			/* 强制更新 */
			forceUpdate()
		}
	}

	useEffect(() => {
		subscribe(handleStoreChange)
	}, [subscribe])

	/*  
        注意
        这个 useEffect 没有依赖项，每次更新都会执行 effect
    */
	useEffect(handleStoreChange)
	return nextValue
}
